﻿using System;
using System.Globalization;

namespace Ucto.ToExcelConvertor
{
	public class ValueToExcelHandler : IValueHandler
	{
		public ValueToExcelHandler(int columnCount, IExcelSheet sheet)
		{
			if (sheet == null)
			{
				throw new ArgumentNullException("sheet");
			}

			this.ColumnCount = columnCount;
			this.Sheet = sheet;

			this.CurrentIndexOfColumn = 1;
			this.CurrentIndexOfRow = 1;
		}

		protected IExcelSheet Sheet { get; private set; }

		protected int ColumnCount { get; private set; }

		protected int CurrentIndexOfColumn { get; private set; }
		protected int CurrentIndexOfRow { get; private set; }

		protected void IncrementIndexes()
		{
			CurrentIndexOfColumn++;
			if (CurrentIndexOfColumn > ColumnCount)
			{
				CurrentIndexOfColumn = 1;
				CurrentIndexOfRow++;
			}
		}

		protected double ToDouble(string value)
		{
			double result = 0;

			try
			{
				result = double.Parse(value, CultureInfo.InvariantCulture);
			}
			catch (Exception ex)
			{
				throw new Exception(
					string.Format("Could not parse value '{0}' to System.Double.", value)
					, ex
					);
			}

			return result;
		}

		public void Handle(string value)
		{
			Sheet[CurrentIndexOfColumn, CurrentIndexOfRow] = ToDouble(value.Trim());
			IncrementIndexes();
		}
	}
}
